package com.company.site.wechat;

import java.io.IOException;
import java.io.PrintWriter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.company.base.common.WeChatConstant;
import com.company.base.utils.CheckUtil;
import com.company.base.utils.Tools;

@Controller
public class WeChatController {
	
	@Resource
	WeChatService weChatService;
	
	/**
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value="wechat",method = RequestMethod.GET)
	public void checkWechat(HttpServletRequest request, HttpServletResponse response) throws IOException{
		PrintWriter out = response.getWriter();
		String signature = request.getParameter("signature");      // 
		String timestamp = request.getParameter("timestamp");      // 
		String nonce = request.getParameter("nonce");              // 
		String echostr = request.getParameter("echostr");          // 
		// 验证
		if (Tools.checkSignature(WeChatConstant.token, signature, timestamp, nonce)) {
			out.write(echostr);
		}
		out.flush();
		out.close();		
	}
	
	/**
	 * 
	 * @param request
	 * @param response
	 * @throws Exception 
	 */
	@RequestMapping(value="wechat",method = RequestMethod.POST)
	public void processWecat(HttpServletRequest request, HttpServletResponse response) throws Exception{ 
		System.out.println("事件推送！");
        request.setCharacterEncoding("UTF-8");  
        response.setCharacterEncoding("UTF-8");    
        String respMessage = weChatService.processRequest(request);          
        if(!CheckUtil.isEmpty(respMessage)){
            PrintWriter out = response.getWriter();  
            out.print(respMessage);  
            out.close(); 
        }   
	}
}
